﻿using QRCoder;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;

namespace LEE.Tools.IO
{
    public class FileHelper
    {

        /// <summary>
        /// 获取文件后缀名（不包含.）
        /// </summary>
        /// <returns></returns>
        public static string GetExtension(string fileName)
        {
            string ext = string.Empty;
            ext = fileName.Substring(fileName.LastIndexOf(".") + 1);
            return ext;
        }
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="filePaths">文件路径集合</param>
        public static void DeleteFiles(List<string> filePaths)
        {
            foreach (var path in filePaths)
            {
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
            }
        }

        /// <summary>
        /// 从指定URL下载文件
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static byte[] GetBytesByUrl(string url)
        {
            ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
            var wc = new WebClient();
            try
            {
                return wc.DownloadData(url);
            }
            finally
            {
                wc.Dispose();
            }
        }

        /// <summary>
        /// 生成二维码byte数组
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static byte[] CreateQrCode(string source)
        {
            QRCodeGenerator qrGenerator = new QRCoder.QRCodeGenerator();
            QRCodeData qrCodeData = qrGenerator.CreateQrCode(source, QRCodeGenerator.ECCLevel.Q);
            QRCode qrcode = new QRCode(qrCodeData);
            Bitmap qrCodeImage = qrcode.GetGraphic(15, Color.Black, Color.White, null, 15, 6, false);
            using (MemoryStream ms = new MemoryStream())
            {
                qrCodeImage.Save(ms, ImageFormat.Jpeg);
                return ms.GetBuffer();
            }
        }
    }
}
